package io.renren.wechat.authen.controller;

import io.renren.common.utils.R;
import io.renren.modules.jxgk.entity.TeacherInfoEntity;
import io.renren.modules.jxgk.service.TeacherInfoService;
import io.renren.modules.jxgkphone.entity.StudentInfo;
import io.renren.modules.jxgkphone.service.StuInfoService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import io.renren.wechat.authen.common.Constant;
import io.renren.wechat.authen.service.LoginService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    SysUserTokenService sysUserTokenService;
    @Autowired
    StuInfoService stuInfoService;
    @Autowired
    TeacherInfoService teacherInfoService;
    @Autowired
    LoginService loginService;
    @RequestMapping("/authorize")
    public String authorize(@RequestParam("returnUrl")String returnUrl, HttpServletRequest request){

//       String url1 = request.getScheme() +"://" + request.getServerName()
//                + ":" +request.getContextPath()+"/"+request.getServerPort()
//                + request.getServletPath();


        String url=Constant.OPENID_PATH;
        String redirectUrl=wxMpService.oauth2buildAuthorizationUrl(url,WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode(returnUrl));
        return "redirect:"+redirectUrl;
    }
    @RequestMapping("/userInfo")
    public String  userInfo(@RequestParam("code")String code,
                         @RequestParam("state")String returnUrl){
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken=new WxMpOAuth2AccessToken();
        try{
            wxMpOAuth2AccessToken=wxMpService.oauth2getAccessToken(code);
            //String jsapi=loginService.getJsapiTicket(wxMpOAuth2AccessToken.getAccessToken());
            String jsapiTicket = wxMpService.getJsapiTicket();




            //3、时间戳和随机字符串
            String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳

            System.out.println("accessToken:"+wxMpOAuth2AccessToken.getAccessToken()+"\njsapi_ticket:"+jsapiTicket+"\n时间戳："+timestamp+"\n随机字符串："+noncestr);

            //4、获取url
            String url="http://xuebing.natapp1.cc";

            //5、将参数排序并拼接字符串
            String str = "jsapi_ticket="+jsapiTicket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
            String signature =Constant.SHA1(str);
            System.out.println("参数："+str+"\n签名："+signature);
            System.out.println(jsapiTicket);
        }catch (WxErrorException e){
            System.out.println("网页授权失败");
        }
        //验证OpenId
        String openId=wxMpOAuth2AccessToken.getOpenId();

        SysUserEntity sysUserEntity=sysUserService.queryByUserOpenId(openId);
        System.out.println("openId:"+openId);
        if(sysUserEntity!=null) {
            //生成token，并保存到数据库
//            StudentInfo studentInfo=stuInfoService.GetStuInfo(sysUserEntity.getUsername());
//            TeacherInfoEntity teacherInfo=teacherInfoService.getTeacherInfo(sysUserEntity.getUsername());
            R r=sysUserTokenService.createToken(sysUserEntity.getUserId());
//            map.put("token",r.get("token"));
            return "redirect:" + Constant.INDEX_PATH + "?token=" + r.get("token");
        }else {
            return "redirect:" + Constant.EEGISTER_PATH + "?openid=" + openId;
        }

    }


}



